package com.example.shirodemo.demos.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("ty")
@Slf4j
public class ThymeleafController {

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/login")
    public String loginpage() {
        return "login";
    }

    public static void main(String[] args) {
        String password = "admin";
        String salt = "abcdefg";
        SimpleHash simpleHash = new SimpleHash("md5", password, salt, 2);
        System.out.println(simpleHash.toString());
    }

    @RequestMapping("/user/login")
    public String login(String username, String password, boolean rememberMe) {
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // 封装凭证
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);

        // 身份认证，失败抛异常
        try {
            currentUser.login(token);
        } catch (UnknownAccountException e) {
            log.error("用户名不存在：" + e.getMessage(), e);
            return "error: 用户名不存在";
        } catch (IncorrectCredentialsException e) {
            log.error("密码错误：" + e.getMessage(), e);
            return "error: 密码错误";
        } catch (Exception e) {
            log.error("未知异常：" + e.getMessage(), e);
            return "error: 未知异常";
        }

        return "index";
    }

    @RequestMapping("logout")
    public String logout() {
        // 清除认证信息，退出
        SecurityUtils.getSubject().logout();
        return "index";
    }

}
